<template>
  <el-upload
  class="avatar-uploader"
  :action="action"
  :data="data.uploadKey"
  :show-file-list="false"
  :on-success="handleAvatarSuccess"
  :before-upload="beforeAvatarUpload">
  <img v-if="imageUrl" :src="imageUrl" class="avatar">
  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</template>

<script>
import { getQinTokenRequest } from '@/api/common'
import { onMounted, reactive, ref } from '@vue/composition-api'
export default {
  props: {
    action: {
      type: String,
      required: true
    }
  },
  setup (props, { root }) {
    // 预览图url
    const imageUrl = ref('')
    // 七牛云token
    const getQinToken = async () => {
      const { data: res } = await getQinTokenRequest()
      data.uploadKey.token = res.data.token
    }
    // 上传图片请求体数据
    const data = reactive({
      uploadKey: {
        token: '',
        key: ''
      }
    })
    // 上传前
    const beforeAvatarUpload = (file) => {
      const key = encodeURI(file.name)
      data.uploadKey.key = key
      // 判断文件类型
      const isJPG = file.type === 'image/jpeg'
      // 判断图片大小是否超过2m
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
    // 上传成功后
    const handleAvatarSuccess = () => {
    }
    onMounted(() => {
      getQinToken()
    })
    return {
      data,
      beforeAvatarUpload,
      handleAvatarSuccess,
      imageUrl
    }
  }
}
</script>

<style>
/* // 图片
    const imageUrl = ref('')
    // 获取七牛token
    const getQinToken = () => {
      getQinTokenRequest().then(res => {
        data.body.token = res.data.data.token
      }).catch(err => console.log(err))
    }
    // 提交的数据
    const data = reactive({
      body: {
        // 七牛token
        token: '',
        // 文件标识
        key: ''
      }

    })
    // 上传前处理
    const beforeAvatarUpload = (file) => {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        root.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        root.$message.error('上传头像图片大小不能超过 2MB!')
      }
      // 把文件名经过url编码作为标识
      const suffix = file.name
      const key = encodeURI(`${suffix}`)
      data.body.key = key
      console.log(data)
      return isJPG && isLt2M
    }
    // 上传成功处理
    const handleAvatarSuccess = (res, file) => {
      console.log(res)
      console.log(file)
    }
    // 生命周期
    onMounted(() => {
      getQinToken()
    })
    return {
      data,
      beforeAvatarUpload,
      handleAvatarSuccess,
      imageUrl
    } */
</style>
